#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
#
import json
import time
from functools import wraps
from typing import Callable, TypeVar, cast

import jwt
import requests
from flask import request

from flask import jsonify

from airflow.patsnap.service import user_service
from airflow.configuration import conf
from airflow.models import User
from airflow.patsnap.util import ops

T = TypeVar("T", bound=Callable)  # pylint: disable=invalid-name


def exception_handle(function: T):
    """Decorator for functions that require authentication"""

    @wraps(function)
    def decorated(*args, **kwargs):
        try:
            return function(*args, **kwargs)
        except Exception as e:
            import traceback
            trace = traceback.format_exc()
            return jsonify(code=500, message=trace, data=None)

    return cast(T, decorated)


def provide_user(func: Callable[..., T]) -> Callable[..., T]:

    @wraps(func)
    def wrapper(*args, **kwargs) -> T:
        token = request.headers.get("Authorization", type=str, default=None)
        if token is None or token == '':
            return jsonify(code=401, message="token is null", data=None)
        if conf.get('webserver', 'login') == 'ldap':
            try:
                jwt_decoder = jwt.decode(token, verify=False)
            except Exception as e:
                return jsonify(code=401, message=str(e), data=None)
            username = str(jwt_decoder["sub"])
            data = {
                "userName": username,
                "token": token
            }
            headers = {
                "Content-Type": "application/json"
            }
            admin_verify = conf.get('webserver', 'admin_verify')
            result = requests.post(admin_verify, data=json.dumps(data), headers=headers, timeout=10)
            result_obj = json.loads(result.text)
            if "ok" == result_obj["message"]:
                try:
                    user = User.get_user_by_oausername(username)
                    if user is None:
                        role_ids = [2]
                        user_service.add_user(username, username, username, 'ldap', role_ids)
                except Exception as e:
                    print(e)
                return func(*args, oa_user_name=username, **kwargs)
            else:
                return jsonify(code=403, message=result.text, data=None)
        elif conf.get('webserver', 'login') == 'ops':
            jwt_decoder = jwt.decode(token, conf.get('webserver', 'jwt_secret'), algorithm="HS512")
            username = jwt_decoder["sub"]
            try:
                user = User.get_user_by_oausername(username)
                if user is None:
                    # 判断用户名是否有效
                    verify_username = ops.verify_username(username)
                    if verify_username:
                        role_ids = [2]
                        user_service.add_user(username, username, username, 'ldap', role_ids)
            except Exception as e:
                print(e)
            return func(*args, oa_user_name=username, **kwargs)
        else:
            jwt_decoder = jwt.decode(token, conf.get('webserver', 'jwt_secret'), algorithm="HS512")
            use_name = jwt_decoder["sub"]
            return func(*args, oa_user_name=use_name, **kwargs)
    return wrapper
